package com.it.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.it.entity.User;
import com.it.mapper.UserMapper;
import com.it.service.IUserService;
import com.it.util.AssertUtil;
import com.it.util.JwtUtil;
import com.it.util.ResultCodeEnum;
import com.it.util.ThreadLocalUtil;
import com.it.vo.LoginVo;
import com.it.vo.RegisterVo;
import com.it.vo.UserInfoVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author 16272
 * @date 2023/09/22
 */
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    UserMapper userMapper;

    @Override
    public String login(LoginVo loginVo) {
//        检测是否已经注册
        User userByUsername = userMapper.findUserByUsername(loginVo.getUsername());
        AssertUtil.isNotEmpty(ResultCodeEnum.UNREGISTERED,userByUsername);
//        校验密码
        String md5Password = DigestUtil.md5Hex(loginVo.getPassword());
        AssertUtil.isTrue(ResultCodeEnum.PARAMETER_ERROR,userByUsername.getPassword().equals(md5Password));
        ThreadLocalUtil.setUserId(userByUsername.getUserId());
        return JwtUtil.createToken(userByUsername.getUsername(),userByUsername.getUserId());
    }

    @Override
    public void register(RegisterVo registerVo) {
        User userByUsername = userMapper.findUserByUsername(registerVo.getUsername());
        AssertUtil.isEmpty(ResultCodeEnum.REGISTERED,userByUsername);
        registerVo.setPassword(DigestUtil.md5Hex(registerVo.getPassword()));
        registerVo.setUserId(IdUtil.getSnowflakeNextId());
        registerVo.setCreateTime(new Date());
        registerVo.setUpdateTime(new Date());
        registerVo.setIsDeleted(0);
        userMapper.addUser(registerVo);
    }

    @Override
    public void updateUser(UserInfoVo userInfoVo) {
        User userByUsername = userMapper.findUserByUsername(userInfoVo.getUsername());
//        判断用户名是否已经存在
        AssertUtil.isEmpty(ResultCodeEnum.REGISTERED, userByUsername);
        userInfoVo.setUpdateTime(new Date());
        userInfoVo.setPassword(DigestUtil.md5Hex(userInfoVo.getPassword()));
        userInfoVo.setUserId(ThreadLocalUtil.getUserId());
        userMapper.updateUser(userInfoVo);
    }

    @Override
    public void deleteUser() {
        Long userId = ThreadLocalUtil.getUserId();
        userMapper.deleteUserByUserId(userId);
        ThreadLocalUtil.removeUserId();
    }
}
